<?php


namespace Biz\service\redPacket;

use Biz\service\redPacket\RedPackets as sRedPackets;
use Biz\model\redPacket\RedPacketsLog as mRedPacketsLog;
use Biz\model\redPacket\RedPacketsSend as mRedPacketsSend;
use Biz\module\Classes\redPacket\RedPacket as clsRedPacket;
use Biz\model\admin\AdminUser as mAdminUser;
use Biz\tools\helper\Common;
use Doraemon\cache\Queue;
use Doraemon\tools\ImgUrl as tImgUrl;
use Doraemon\service\User as sUser;
use Biz\pockets\serviceTrait\_Async;

class RedPacketsSend
{
    use _Async;

    public static function sendToUser($adminUid, $postData)
    {
        $packetAmount = $postData['packet_amount'];
        $uidList = $postData['uid_list'];
        $reason = $postData['reason'];
        $sysMsgData = [
            'img_url' => isset($postData['img_url']) ? $postData['img_url'] : '',
            'title' => isset($postData['title']) ? $postData['title'] : '',
            'content' => isset($postData['content']) ? $postData['content'] : '',
            'redirect_url' => isset($postData['redirect_url']) ? $postData['redirect_url'] : '',
        ];
        $uidList = str_replace("\r\n", ',', $uidList);
        $uidToList = array_filter(explode(",", $uidList));
        $uidToList = array_unique($uidToList);
        $pushId = mRedPacketsSend::addData([
            'packet_amount' => $packetAmount,
            'uid_list' => implode(',', $uidToList),
            'reason' => $reason,
            'img_url' => $sysMsgData['img_url'],
            'title' => $sysMsgData['title'],
            'content' => $sysMsgData['content'],
            'redirect_url' => $sysMsgData['redirect_url'],
            'status' => mRedPacketsSend::STATUS_UNSEND,
            'addtime' => date('Y-m-d H:i:s'),
            'admin_uid' => $adminUid
        ]);

        if (empty($pushId)) {
            throw new \Exception('红包发放失败');
        }


        //用户UID列表
        $uidList = array_filter($uidToList);
        //开始启动分批发送
        foreach ($uidList as $uid) {
            self::_async($pushId, $uid, $packetAmount, $reason, $sysMsgData);
        }
        return true;
    }

    public static function _async_SendToUser($pushId, $uid, $packetAmount, $reason, $sysMsgData)
    {
        if ($packetAmount) {
            //发放红包
            $result = clsRedPacket::award($uid, 0, '', $packetAmount, true, $reason);
            if (!$result) {
                mRedPacketsSend::updateData(['status' => mRedPacketsSend::STATUS_DELETE], ['id' => $pushId]);
            }
            mRedPacketsSend::updateData(['status' => mRedPacketsSend::STATUS_SEND], ['id' => $pushId]);
            if (empty($sysMsgData)) {
                return true;
            }
            if (empty($sysMsgData['title']) && empty($sysMsgData['content']) && empty($sysMsgData['img_url'])) {
                return true;
            }
            //发送系统消息
            Queue::insertQueue('queue/Sysmsg/Send',
                [
                    'msgCode' => 0,
                    'to_uid' => $uid,
                    'msgParams' => [
                        'title' => $sysMsgData['title'],
//                        'link' => $sysMsgData['redirect_url'] ? 'hhz://urlb:' . base64_encode($sysMsgData['redirect_url']) : '',
                        'link' => $sysMsgData['redirect_url'] ? Common::formatLinkNormalLink($sysMsgData['redirect_url']) : '',
                        'img' => !empty($sysMsgData['img_url']) ? tImgUrl::getUrl(tImgUrl::APPTYPE_OP, $sysMsgData['img_url'], tImgUrl::IMAGE_SIZE_OP_ORI) : '',
                        'detail' => $sysMsgData['content']
                    ]
                ], Queue::QUEUE_DORAEMON);
        }
    }

    public static function sendList($where = [])
    {
        $list = mRedPacketsSend::select('*', $where);

        $adminUidList = array_column($list, 'admin_uid');
        $adminUserList = mAdminUser::getAdminList($adminUidList);

        $list = array_map(function ($v) use ($adminUserList) {
            mRedPacketsSend::formatInfo($v);

            $v['admin_user'] = [
                'admin_uid' => $v['admin_uid'],
                'admin_name' => $adminUserList[$v['admin_uid']]['name']
            ];
            return $v;
        }, $list);

        $result['list'] = $list;
        unset($where['ORDER'], $where['LIMIT']);
        $result['total'] = mRedPacketsSend::count('id', $where);
        return $result;
    }

    public static function sendUserList($pushId)
    {
        $info = mRedPacketsSend::get(['uid_list', 'packet_amount'], ['id' => $pushId]);

        $userIdList = explode(',', $info['uid_list']);

        $users = sUser::getUserInfoByIds($userIdList);
        $list = [];
        foreach ($users as $row) {
            $list[] = [
                'uid' => $row['uid'],
                'nick' => $row['nick'],
                'packet_amount' => $info['packet_amount']
            ];
        }
        return $list;
    }


}